package Leetcode第一期;

public class 寻找两个有序数组的中位数_4 {
    public static void main(String[] args) {
        int[] num1=new int[]{};
        int[] num2=new int[]{2};
        double res=findMedianSortedArrays(num1,num2);
        System.out.println(res);
    }

    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int n = nums1.length;
        int m = nums2.length;
        int[] h = new int[n + m];
        if (m == 0) {
            if (n % 2 == 0) {
                return (nums1[n / 2 - 1] + nums1[n / 2]) / 2.0;
            } else {

                return nums1[n / 2];
            }
        }

        if (n == 0) {
            if (m % 2 == 0) {
                return (nums2[m / 2 - 1] + nums2[m / 2]) / 2.0;
            } else {
                return nums2[m / 2];
            }
        }

        int i = 0, j = 0;
        int count = 0;
        while (i < n || j < m) {
            if (nums1[i] < nums2[j]) {
                h[count] = nums1[i];
                i++;
            } else {
                h[count] = nums2[j];
                j++;
            }
            count++;
            if (i == n) {
                while (j != m) {
                    h[count++] = nums2[j];
                    j++;
                }
            }
            if (j == m) {
                while (i != n) {
                    h[count++] = nums1[i];
                    i++;
                }
            }
        }

        if (count % 2 == 0) {
            return (h[count / 2 - 1] + h[count / 2]) / 2.0;
        } else {
            return h[count / 2];
        }



    }
}
